<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">库存管理</span>
          <el-button v-hasPermi="['device:stock:add']" type="primary" plain icon="Plus" @click="handleAdd">新增库存</el-button>
        </div>
      </template>

      <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="设备名称" prop="deviceId">
          <el-select
            v-model="queryParams.deviceId"
            placeholder="请选择设备"
            clearable
            style="width: 200px"
            filterable
            :loading="deviceLoading"
            @visible-change="handleDeviceDropdownVisible"
            @change="handleDeviceChange"
          >
            <el-option v-for="item in deviceOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="通道编号" prop="channelId">
          <el-select v-model="queryParams.channelId" placeholder="请选择通道" clearable style="width: 200px">
            <el-option v-for="item in channelOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="商品编号" prop="productNo">
          <el-input v-model="queryParams.productNo" placeholder="请输入商品编号" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="库存状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择库存状态" clearable style="width: 200px">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-hasPermi="['device:stock:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-hasPermi="['device:stock:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
            >删除</el-button
          >
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
      </el-row>

      <div class="table-container">
        <el-table v-loading="loading" :data="stockList" border stripe style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="45" align="center" fixed="left" />
          <el-table-column label="库存ID" align="center" prop="id" min-width="80" />
          <el-table-column label="设备信息" align="center" min-width="180">
            <template #default="scope">
              <div>{{ scope.row.deviceName }}</div>
              <div class="text-secondary">ID: {{ scope.row.deviceId }}</div>
            </template>
          </el-table-column>
          <el-table-column label="通道信息" align="center" min-width="120">
            <template #default="scope">
              <div>{{ scope.row.channelName }}</div>
              <div class="text-secondary">ID: {{ scope.row.channelId }}</div>
            </template>
          </el-table-column>
          <el-table-column label="商品信息" align="center" min-width="200">
            <template #default="scope">
              <div>{{ scope.row.productName }}</div>
              <div class="text-secondary">编号: {{ scope.row.productNo }}</div>
            </template>
          </el-table-column>
          <el-table-column label="库存数量" align="center" width="100">
            <template #default="scope">
              <el-tag :type="getStockQuantityType(scope.row)" effect="dark">
                {{ scope.row.stockQuantity }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="库存限制" align="center" width="180">
            <template #default="scope">
              <div>最大: {{ scope.row.maxQuantity }}</div>
              <div>最小: {{ scope.row.minQuantity }}</div>
              <div>预警: {{ scope.row.alertQuantity }}</div>
            </template>
          </el-table-column>
          <el-table-column label="库存状态" align="center" prop="status" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="dark">
                {{ scope.row.statusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updateTime" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="150" fixed="right">
            <template #default="scope">
              <el-button v-hasPermi="['device:stock:edit']" type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button v-hasPermi="['device:stock:remove']" type="danger" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      </div>
    </el-card>

    <!-- 添加或修改库存对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body destroy-on-close>
      <el-form ref="stockRef" v-loading="dialogLoading" :model="form" :rules="rules" label-width="90px" class="dialog-form">
        <el-form-item label="设备" prop="deviceId">
          <el-select
            v-model="form.deviceId"
            placeholder="请选择设备"
            style="width: 100%"
            :loading="deviceLoading"
            filterable
            remote
            :remote-method="handleDeviceSearch"
            @visible-change="handleDeviceDropdownVisible"
            @change="handleDeviceChange"
          >
            <el-option v-for="item in deviceOptions" :key="item.id" :label="item.deviceName" :value="item.id">
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.deviceName }}</span>
                <span class="text-secondary" style="color: #8492a6; font-size: 13px">
                  {{ item.model }}
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="通道" prop="channelId">
          <el-select
            v-model="form.channelId"
            placeholder="请选择通道"
            style="width: 100%"
            :disabled="!form.deviceId"
            :loading="dialogLoading"
            @change="handleChannelChange"
          >
            <el-option
              v-for="item in channelOptions"
              :key="item.id"
              :label="item.channelName"
              :value="item.id"
              :disabled="usedChannelIds.has(item.id) && (!form.id || form.channelId !== item.id)"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.channelName }}</span>
                <div style="display: flex; align-items: center; gap: 8px">
                  <span class="text-secondary" style="color: #909399; font-size: 13px"> 容量: {{ item.maxCapacity }} </span>
                  <span
                    v-if="usedChannelIds.has(item.id) && (!form.id || form.channelId !== item.id)"
                    class="text-secondary"
                    style="color: #f56c6c; font-size: 13px"
                  >
                    已使用
                  </span>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品" prop="productId">
          <el-select
            v-model="form.productId"
            placeholder="请选择商品"
            style="width: 100%"
            filterable
            remote
            :remote-method="handleProductSearch"
            :loading="productLoading"
            @visible-change="handleProductDropdownVisible"
            @change="handleProductSearch"
          >
            <el-option v-for="item in productOptions" :key="item.id" :label="item.name" :value="item.id">
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.name }}</span>
                <span class="text-secondary" style="color: #8492a6; font-size: 13px">
                  {{ item.productNo }}
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input-number v-model="form.stockQuantity" :min="0" :max="form.maxQuantity || 99999" placeholder="请输入库存数量" style="width: 100%" />
        </el-form-item>

        <el-form-item label="最大库存" prop="maxQuantity">
          <el-input-number
            v-model="form.maxQuantity"
            :min="Math.max(form.minQuantity || 0, form.alertQuantity || 0, form.stockQuantity || 0)"
            :max="selectedChannelMaxCapacity || 99999"
            placeholder="请输入最大库存量"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="预警库存" prop="alertQuantity">
          <el-input-number
            v-model="form.alertQuantity"
            :min="form.minQuantity || 0"
            :max="form.maxQuantity || selectedChannelMaxCapacity || 99999"
            placeholder="请输入预警库存量"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="最小库存" prop="minQuantity">
          <el-input-number
            v-model="form.minQuantity"
            :min="0"
            :max="form.alertQuantity || form.maxQuantity || selectedChannelMaxCapacity || 99999"
            placeholder="请输入最小库存量"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="dialogLoading" @click="submitForm">确 定</el-button>
          <el-button :disabled="dialogLoading" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Stock">
import { listStock, getStock, delStock, addStock, updateStock } from '@/api/vending/stock';
import { ref, getCurrentInstance, onMounted, watch, computed, nextTick } from 'vue';
import { getDeviceList } from '@/api/vending/device';
import { getChannelList } from '@/api/vending/channel';
import { listProduct } from '@/api/product/product';
import { debounce } from 'lodash-es';

const { proxy } = getCurrentInstance();

// 本地缓存
const deviceCache = ref(new Map());
const productCache = ref(new Map());
const channelCache = ref(new Map());

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 库存表格数据
const stockList = ref([]);

const stockList1 = ref([]);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);

// 设备选项
const deviceOptions = ref([]);
// 所有通道列表
const allChannelOptions = ref([]);
// 当前设备对应的通道列表
const channelOptions = ref([]);
// 已使用的通道ID列表
const usedChannelIds = ref(new Set());

// 商品选项
const productOptions = ref([]);
// 商品加载状态
const productLoading = ref(false);

// 表单ref
const stockRef = ref();
const queryRef = ref();

// 库存状态字典
const statusOptions = ref([
  { value: 0, label: '缺货' },
  { value: 1, label: '正常' },
  { value: 2, label: '超量' }
]);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  deviceId: undefined,
  channelId: undefined,
  productName: undefined,
  productNo: undefined,
  status: undefined
});

// 表单参数
const form = ref({
  id: undefined,
  deviceId: undefined,
  channelId: undefined,
  productId: undefined,
  stockQuantity: 0,
  maxQuantity: 0,
  minQuantity: 0,
  alertQuantity: 0,
  status: 1
});
// 表单校验
const rules = ref({
  deviceId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }],
  channelId: [{ required: true, message: '通道ID不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '商品ID不能为空', trigger: 'blur' }],
  stockQuantity: [{ required: true, message: '库存数量不能为空', trigger: 'blur' }],
  maxQuantity: [{ required: true, message: '最大库存量不能为空', trigger: 'blur' }],
  minQuantity: [{ required: true, message: '最小库存量不能为空', trigger: 'blur' }],
  alertQuantity: [{ required: true, message: '预警库存量不能为空', trigger: 'blur' }]
});

// 对话框加载状态
const dialogLoading = ref(false);

// 添加计算属性
const selectedChannel = computed(() => {
  return channelOptions.value.find((item) => item.id === form.value.channelId);
});

const selectedChannelMaxCapacity = computed(() => {
  return selectedChannel.value?.maxCapacity || 0;
});

// 设备加载状态
const deviceLoading = ref(false);

// 延迟加载标志
const isDeviceOptionsLoaded = ref(false);
const isProductOptionsLoaded = ref(false);

// 防抖处理
const debouncedDeviceSearch = debounce((keyword: string) => {
  handleDeviceSearch(keyword);
}, 300);

const debouncedProductSearch = debounce((keyword: string) => {
  handleProductSearch(keyword);
}, 300);

// 优化表格数据加载
const displayData = computed(() => {
  return stockList.value;
});

// 优化列表查询
const getList = async () => {
  if (loading.value) return;
  loading.value = true;
  try {
    const response = await listStock({
      ...queryParams.value,
      pageSize: 10 // 固定每页大小
    });
    stockList.value = response.rows || [];
    total.value = response.total;
  } catch (error) {
    console.error('获取库存列表失败:', error);
    proxy.$modal.msgError('获取库存列表失败');
  } finally {
    loading.value = false;
    getDeviceStock();
  }
};

const getDeviceStock = async () => {
  try {
    const response = await listStock({
      ...queryParams.value,
      pageSize: 999 // 固定每页大小
    });
    stockList1.value = response.rows || [];
    total.value = response.total;
  } catch (error) {
    console.error('获取库存列表失败:', error);
    proxy.$modal.msgError('获取库存列表失败');
  }
};

// 设备搜索
const handleDeviceSearch = async (query = '') => {
  if (!query && isDeviceOptionsLoaded.value) return;

  deviceLoading.value = true;
  try {
    const response = await getDeviceList({
      name: query,
      pageNum: 1,
      pageSize: 10
    });
    deviceOptions.value = response.rows || [];
    if (!query) isDeviceOptionsLoaded.value = true;
  } finally {
    deviceLoading.value = false;
  }
};

// 商品搜索
const handleProductSearch = async (query = '') => {
  // console.log(query)
  // if (isProductOptionsLoaded.value) return;

  productLoading.value = true;
  try {
    const response = await listProduct({
      name: query,
      pageNum: 1,
      pageSize: 10
    });
    productOptions.value = response.rows || [];
    // if (!query) isProductOptionsLoaded.value = true;
  } finally {
    productLoading.value = false;
  }
};

// 通道加载 - 仅在选择设备时加载
const loadChannels = async (deviceId) => {
  if (!deviceId) {
    channelOptions.value = [];
    return;
  }

  dialogLoading.value = true;
  try {
    const response = await getChannelList({ deviceId });
    // channelOptions.value = response.data || [];
    if (response && response.data) {
      channelOptions.value = response.data.map((item) => ({
        id: item.id,
        channelName: `${item.channelNo} (${item.channelPosition})`,
        deviceId: item.deviceId,
        maxCapacity: item.maxCapacity
      }));
      // console.log(allChannelOptions.value);
      // updateUsedChannels();
    } else {
      allChannelOptions.value = [];
      channelOptions.value = [];
      console.warn('通道列表数据格式不正确:', response);
    }
  } finally {
    dialogLoading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = debounce(() => {
  queryParams.value.pageNum = 1;
  getList();
}, 300);

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  getList();
};

// 下拉框显示时才加载数据
const handleDeviceDropdownVisible = (visible) => {
  if (visible && !isDeviceOptionsLoaded.value) {
    handleDeviceSearch();
  }
};

const handleProductDropdownVisible = (visible) => {
  if (visible && !isProductOptionsLoaded.value) {
    handleProductSearch();
  }
};

// 设备选择变化时加载通道
const handleDeviceChange = (deviceId) => {
  if (deviceId) {
    loadChannels(deviceId);
  } else {
    channelOptions.value = [];
  }
};

// 组件挂载时只加载表格数据
onMounted(() => {
  getList();
});

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  // selectedChannelMaxCapacity.value = 8;
  form.value = {
    id: undefined,
    deviceId: undefined,
    channelId: undefined,
    productId: undefined,
    minQuantity: 0,
    stockQuantity: 0,
    alertQuantity: 0,
    maxQuantity: selectedChannelMaxCapacity.value || 0,
    status: '1'
  };
  stockRef.value?.resetFields();
  productOptions.value = [];
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  reset();
  // 设置合理的默认值，保证顺序
  const maxQuantity = 10;
  const alertQuantity = Math.min(3, maxQuantity);
  const minQuantity = Math.min(1, alertQuantity);
  const stockQuantity = Math.min(5, maxQuantity);
  form.value = {
    deviceId: deviceOptions.value.length > 0 ? deviceOptions.value[0].id : undefined,
    channelId: undefined,
    productId: productOptions.value.length > 0 ? productOptions.value[0].id : undefined,
    stockQuantity,
    maxQuantity,
    minQuantity,
    alertQuantity,
    status: 1
  };
  dialogLoading.value = true;
  try {
    await Promise.all([fetchDeviceList(), fetchChannelList()]);
    open.value = true;
    title.value = '添加库存';
  } finally {
    dialogLoading.value = false;
  }
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  dialogLoading.value = true;
  try {
    const id = row.id || ids.value[0];
    const [deviceResponse, channelResponse, stockResponse] = await Promise.all([fetchDeviceList(), fetchChannelList(), getStock(id)]);
    // console.log('stockResponse', stockResponse);
    if (!stockResponse?.data) {
      proxy.$modal.msgError('获取库存信息失败');
      return;
    }

    const data = stockResponse.data;

    // 先设置设备ID，这会触发通道列表的更新
    form.value.deviceId = data.deviceId;

    // 等待通道列表更新完成
    await new Promise((resolve) => setTimeout(resolve, 100));

    // 设置选中通道的最大容量
    const selectedChannel = channelOptions.value.find((item) => item.id === data.channelId);
    const maxCapacity = selectedChannel?.maxCapacity || 0;
    selectedChannelMaxCapacity.value = maxCapacity;

    // 确保数值之间的关系正确
    const maxQuantity = Math.min(data.maxQuantity || 0, maxCapacity);
    const alertQuantity = Math.min(data.alertQuantity || 0, maxQuantity);
    const minQuantity = Math.min(data.minQuantity || 0, alertQuantity);
    const stockQuantity = Math.min(data.stockQuantity || 0, maxQuantity);

    // 设置完整的表单数据
    form.value.id = data.id;
    form.value.deviceId = data.deviceId;
    form.value.channelId = data.channelId;
    form.value.productId = data.productId;
    form.value.stockQuantity = stockQuantity;
    form.value.maxQuantity = maxQuantity;
    form.value.minQuantity = minQuantity;
    form.value.alertQuantity = alertQuantity;
    form.value.status = data.status;
    // 加载当前商品信息
    if (data.productId) {
      handleProductSearch(data.productName);
    }

    open.value = true;
    title.value = '修改库存';
  } catch (error) {
    console.error('修改库存失败:', error);
    proxy.$modal.msgError('修改库存失败');
  } finally {
    dialogLoading.value = false;
  }
}

/** 提交按钮 */
async function submitForm() {
  try {
    const valid = await stockRef.value?.validate();
    if (valid) {
      dialogLoading.value = true;
      if (form.value.id != undefined) {
        console.log(form.value);
        form.value.deviceName == null;
        await updateStock(form.value);
        proxy.$modal.msgSuccess('修改成功');
      } else {
        await addStock(form.value);
        proxy.$modal.msgSuccess('新增成功');
      }
      open.value = false;
      getList();
    }
  } catch (error) {
    console.error('提交表单失败:', error);
    proxy.$modal.msgError('操作失败');
  } finally {
    dialogLoading.value = false;
  }
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    const stockIds = row.id || ids.value;
    await proxy.$modal.confirm('是否确认删除库存编号为"' + stockIds + '"的数据项？');
    await delStock(stockIds);
    getList();
    proxy.$modal.msgSuccess('删除成功');
  } catch (error) {
    console.error('删除失败:', error);
  }
}

// 获取设备列表
async function fetchDeviceList() {
  try {
    deviceLoading.value = true;
    const response = await getDeviceList({
      pageNum: 1,
      pageSize: 10
    });
    if (response?.rows) {
      deviceOptions.value = response.rows.map((item) => ({
        id: item.id,
        deviceName: `${item.deviceName} (${item.deviceNo})`,
        model: item.model
      }));
      // console.log(deviceOptions.value);
    } else {
      deviceOptions.value = [];
    }
  } catch (error) {
    console.error('获取设备列表失败:', error);
    deviceOptions.value = [];
  } finally {
    deviceLoading.value = false;
  }
}

// 获取通道列表
function fetchChannelList() {
  return getChannelList()
    .then((response) => {
      // console.log('通道列表响应:', response);
      if (response && response.data) {
        allChannelOptions.value = response.data.map((item) => ({
          id: item.id,
          channelName: `${item.channelNo} (${item.channelPosition})`,
          deviceId: item.deviceId,
          maxCapacity: item.maxCapacity
        }));
        // console.log(allChannelOptions.value);
        updateUsedChannels();
      } else {
        allChannelOptions.value = [];
        channelOptions.value = [];
        // console.warn('通道列表数据格式不正确:', response);
      }
    })
    .catch((error) => {
      console.error('获取通道列表失败:', error);
      allChannelOptions.value = [];
      channelOptions.value = [];
    });
}

// 更新已使用的通道ID
function updateUsedChannels() {
  usedChannelIds.value = new Set(stockList1.value.map((item) => item.channelId));
}

// 处理通道选择变化
function handleChannelChange(channelId) {
  const adjustments = {
    maxQuantity: Math.min(form.value.maxQuantity, selectedChannelMaxCapacity.value),
    alertQuantity: Math.min(form.value.alertQuantity, form.value.maxQuantity),
    minQuantity: Math.min(form.value.minQuantity, form.value.alertQuantity),
    stockQuantity: Math.min(form.value.stockQuantity, form.value.maxQuantity)
  };

  Object.entries(adjustments).forEach(([key, value]) => {
    form.value[key] = value;
  });
}

// 监听设备选择变化
watch(
  () => form.value.deviceId,
  (newDeviceId) => {
    if (newDeviceId) {
      channelOptions.value = allChannelOptions.value.filter((item) => item.deviceId === newDeviceId);
      if (form.value.channelId && !channelOptions.value.some((item) => item.id === form.value.channelId)) {
        form.value.channelId = undefined;
      }
    } else {
      channelOptions.value = [];
      form.value.channelId = undefined;
    }
  },
  { immediate: true }
);

// 监听库存列表变化
watch(
  () => stockList.value,
  () => {
    updateUsedChannels();
  },
  { deep: true }
);

// 获取库存数量状态类型
function getStockQuantityType(row) {
  if (row.stockQuantity <= row.minQuantity) {
    return 'danger';
  } else if (row.stockQuantity <= row.alertQuantity) {
    return 'warning';
  }
  return 'success';
}

// 清理缓存的辅助函数
function clearCache() {
  deviceCache.value.clear();
  productCache.value.clear();
  channelCache.value.clear();
}

// 组件卸载时清理缓存
onUnmounted(() => {
  clearCache();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;

  .box-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-bottom: 0;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 16px;
      overflow: hidden;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;

      .title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        position: relative;
        padding-left: 12px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 16px;
          background-color: #409eff;
          border-radius: 2px;
        }
      }
    }
  }

  .search-form {
    margin-bottom: 16px;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .mb8 {
    margin-bottom: 12px;
  }

  .stock-warning {
    color: #f56c6c;
    font-weight: 600;
  }

  .text-secondary {
    color: #909399;
    font-size: 13px;
  }

  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .stock-table {
    flex: 1;
    margin-top: 12px;
    margin-bottom: 16px;

    :deep(.el-table__header-wrapper) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
        height: 48px;
        padding: 8px 0;
      }
    }

    :deep(.el-table__body-wrapper) {
      td {
        padding: 12px 0;
      }
    }

    :deep(.el-table__row) {
      transition: all 0.3s ease;

      &:hover {
        background-color: #f5f7fa;
      }

      .el-tag {
        min-width: 60px;
        border-radius: 4px;
        padding: 0 8px;
        height: 24px;
        line-height: 24px;
      }
    }
  }

  .pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
    padding: 8px 0;
  }

  :deep(.el-dialog) {
    border-radius: 8px;
    overflow: hidden;

    .el-dialog__header {
      margin-right: 0;
      border-bottom: 1px solid #ebeef5;
      padding: 16px 20px;
      background-color: #f5f7fa;

      .el-dialog__title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    .el-dialog__body {
      padding: 24px;
      min-height: 200px;
    }

    .dialog-footer {
      padding: 16px 20px;
      text-align: right;
      border-top: 1px solid #ebeef5;
      background-color: #f5f7fa;
    }

    .dialog-form {
      .el-form-item {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
        }
      }

      .el-input-number {
        width: 100%;

        .el-input__wrapper {
          padding: 0 8px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  :deep(.el-input-number) {
    width: 100%;
  }

  :deep(.el-button) {
    border-radius: 4px;
    font-weight: 500;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

/* 添加虚拟滚动相关样式 */
.table-container {
  position: relative;
  height: calc(100vh - 300px);
  overflow: hidden;

  .stock-table {
    // 开启硬件加速
    transform: translateZ(0);

    :deep(.el-table__body-wrapper) {
      overflow-y: auto;
      height: calc(100% - 40px); // 减去表头高度

      // 优化滚动性能
      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 3px;
        background: #c0c4cc;
      }

      &::-webkit-scrollbar-track {
        background: #f5f7fa;
      }

      // 使用 will-change 提示浏览器优化
      will-change: transform;

      // 使用 contain 优化重绘
      contain: strict;
    }

    // 优化表格行渲染
    :deep(.el-table__row) {
      contain: layout style paint;
    }
  }
}

/* 优化选择器下拉框的性能 */
.el-select-dropdown__list {
  contain: content;
}

/* 使用 CSS containment 优化渲染性能 */
.el-table__body-wrapper {
  contain: content;
}

/* 添加性能优化相关的样式 */
.performance-optimized {
  // 开启 GPU 加速
  transform: translateZ(0);
  // 优化重绘区域
  contain: content;
  // 提示浏览器优化
  will-change: transform;
}
</style>
